'use strict'

import { app, BrowserWindow, ipcMain, shell } from 'electron'
import { autoUpdater } from 'electron-updater'
import log from 'electron-log'
import config from '../../package.json'
import request from 'request'
import progress from 'request-progress'
import patchFs from 'electron-patch-fs'
import fs from 'fs'
import os from 'os'
import path from 'path'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */

if (process.env.NODE_ENV !== 'development') {
  global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
let isZhuxiao = false
const IS_DEV = process.env.NODE_ENV === 'development'
const winURL = IS_DEV ? `http://localhost:9080` : `file://${__dirname}/index.html`

function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    width: 393,
    height: 500,
    resizable: false,
    transparent: true,
    frame: false,
    webPreferences: {
      webSecurity: !IS_DEV
    }
  })

  mainWindow.loadURL(winURL)

  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('mainWindow is not defined')
    }
    mainWindow.show()
    mainWindow.focus()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

app.on('will-quit', (event) => {
  if (isZhuxiao) {
    isZhuxiao = false
    event.preventDefault()
    createWindow()
  }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

// autoUpdater.on('update-downloaded', () => {
//   autoUpdater.quitAndInstall()
// })
//
// app.on('ready', () => {
//   if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
// })

let updateChannel
let sendMsg = {
  percent: 0,
  msg: '',
  success: false,
  isreStart: false
}

function sendToUpdateChannel (jsonMsg) {
  updateChannel.sender.send('_checkUpdatesMessage', jsonMsg)
}

// 下载更新
function downloadSmallUpdates () {
  // 发送请求是否有更新
  // 直接下载文件 http://meiyitong.oss-cn-shanghai.aliyuncs.com/app.asar
  let speed = 0,
    size = 0,
    percent = 0

  patchFs.patch()
  progress(request('http://meiyitong.oss-cn-shanghai.aliyuncs.com/app.asar'))
    .on('progress', function (state) {
      // 开始下载更新
      // 下载速度，总计大小， 百分比

      // 获取速度
      speed = (state.speed / 1024).toFixed(2)
      speed = speed > 1024 ? (speed / 1024).toFixed(2) + 'M/s' : speed + 'kb/s'
      // 大小
      size = (state.size.total / 1024).toFixed(2)
      size = size > 1024 ? (size / 1024).toFixed(2) + 'M' : size + 'kb'
      // 百分比
      percent = (state.percent * 100).toFixed(2) + '%'

      sendMsg.percent = percent
      sendMsg.msg = `正在更新，总计${size}, 速度${speed}, 进度${percent}`

      // 发送数据
      sendToUpdateChannel(sendMsg)
    })
    .on('end', function () {
      sendMsg.percent = '100%'
      sendMsg.msg = '开始替换文件！'
      sendToUpdateChannel(sendMsg)
    })
    .pipe(fs.createWriteStream('./resources/app.asar'))
    .on('finish', () => {
      // 执行加载函数
      patchFs.unpatch()
      sendMsg.success = true
      sendMsg.isreStart = true
      // 等待patchFs.unpatch()执行完成延时执行
      sendToUpdateChannel(sendMsg)
    })
}

// 判断v1是否大于v2
function checkBigVersion (v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  // 先用文字描述逻辑
  // 首先如果主版本1大于主版本2，说明1大
  // 如果主版本1等于主版本2 继续往下比较
  let i = 0
  let len = v1.length
  while (i < len) {
    if (Number(v1[i]) === Number(v2[i])) {
      i++
      continue
    }
    return Number(v1[i]) > Number(v2[i])
  }
  return false
}

// 检查更新
function checkUpdates () {
  // http://meiyitong.oss-cn-shanghai.aliyuncs.com/app.txt
  request('http://meiyitong.oss-cn-shanghai.aliyuncs.com/app.json', function (err, response, body) {
    // 如果错误提示更新失败请重启
    if (err) {
      sendMsg.msg = '更新失败请重启!'
      sendToUpdateChannel(sendMsg)
      return false
    }
    if (response.statusCode === 404) {
      sendMsg.percent = '100%'
      sendMsg.success = true
      sendToUpdateChannel(sendMsg)
    } else {
      let newVersion = JSON.parse(body)
      // 先判断服务器上的包是不是当前版本的包
      if (checkBigVersion(newVersion.smallVersion, config.smallVersion)) {
        // 执行更新操作
        downloadSmallUpdates()
      } else {
        // 已经是最新包
        sendMsg.percent = '100%'
        sendMsg.success = true
        sendToUpdateChannel(sendMsg)
      }
    }
  })
}

// 日志初始化操作
autoUpdater.logger = log
autoUpdater.logger.transports.file.level = 'info'

log.info(process.env.NODE_ENV)
log.info('App starting.....')

autoUpdater.on('checking-for-update', (ev, info) => {
  sendMsg.msg = '开始检全局更新...'
  sendToUpdateChannel(sendMsg)
})
// 没有大版本更新检查小版本更新
autoUpdater.on('update-not-available', (ev, info) => {
  sendMsg.msg = '开始检查局部更新...'
  sendToUpdateChannel(sendMsg)
  checkUpdates()
})
// 有更新时操作
autoUpdater.on('update-available', (ev, info) => {
  // 有更新开更新窗口
  sendMsg.msg = '开始下载更新！'
  sendToUpdateChannel(sendMsg)
})
// 错误提示
autoUpdater.on('error', (ev, err) => {
  sendMsg.msg = '网络错误，请重新启动程序！'
  sendMsg.percent = '100%'
  sendMsg.success = true
  sendToUpdateChannel(sendMsg)
})
// 更新进度
autoUpdater.on('download-progress', (ev, progressObj) => {
  // 获取速度
  let speed = 0,
    size = 0,
    percent = 0
  speed = (ev.bytesPerSecond / 1024).toFixed(2)
  speed = speed > 1024 ? (speed / 1024).toFixed(2) + 'M/s' : speed + 'kb/s'
  // 大小
  size = (ev.total / 1024).toFixed(2)
  size = size > 1024 ? (size / 1024).toFixed(2) + 'M' : size + 'kb'
  // 百分比
  percent = ev.percent.toFixed(2) + '%'

  sendMsg.percent = percent
  sendMsg.msg = `正在更新，总计${size}, 速度${speed}, 进度${percent}`

  sendToUpdateChannel(sendMsg)
})
// 退出并安装
autoUpdater.on('update-downloaded', (ev, info) => {
  autoUpdater.quitAndInstall()
})

// 监听更新事件
ipcMain.on('_checkUpdates', (event) => {
  updateChannel = event
  // 大版本更新
  if (IS_DEV) {
    sendMsg.percent = '100%'
    sendMsg.success = true
    sendToUpdateChannel(sendMsg)
  } else {
    autoUpdater.checkForUpdates()
  }
  // checkUpdates()
})

// 监听注销事件
ipcMain.on('zhuxiao', (event) => {
  isZhuxiao = true
  app.quit()
})

// 打印操作
ipcMain.on('print-now', function (event) {
  let win = BrowserWindow.fromWebContents(event.sender)
  win.webContents.print({ silent: true, printBackground: false })
})

ipcMain.on('print-to-pdf', function (event) {
  let pdfPath = path.join(os.tmpdir(), 'print.pdf')
  let win = BrowserWindow.fromWebContents(event.sender)
  win.webContents.printToPDF({ marginsType: 1, pageSize: { width: 70000, height: 210000 } }, function (error, data) {
    if (error) throw error
    fs.writeFile(pdfPath, data, function (error) {
      if (error) {
        throw error
      }
      shell.openExternal('file://' + pdfPath)
      // event.sender.send('wrote-pdf', pdfPath)
    })
  })
})
